package com.lv.common.utils

/**
 * 作者： ygx
 * 创建日期：2023/11/27 9:22 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：手机定位
 */
import android.annotation.SuppressLint
import android.content.Context
import android.location.*
import android.os.Bundle
import com.blankj.utilcode.util.LogUtils
import java.util.*

class LocationUtil(val context: Context) {

    private var locationManager: LocationManager? = null
    private var locationListener: LocationListener? = null

    var locationCallBack: (Location) -> Unit = {}

    // 初始化调用
    fun initLocationManager() {
        locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager?
        if (!isOPenGPS(context)) {
            return showToast("未开启GPS定位，无法获取地理位置")
        }
//        if (isToSetting && locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) {
//            // 转到手机设置界面，用户设置GPS
//            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//            context.startActivity(intent)
//        }
        locationListener = object : LocationListener {

            override fun onLocationChanged(location: Location) {
                if (location == null) {
                    return
                }
//                val latitude = location.latitude
//                val longitude = location.longitude
//                val loactionLatLon = GPSUtil.gps84_To_Gcj02(latitude, longitude)
//                location.latitude = loactionLatLon[0]
//                location.longitude = loactionLatLon[1]
                locationCallBack(location)
                release()
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            }

            override fun onProviderEnabled(provider: String) {
            }

            override fun onProviderDisabled(provider: String) {
//                if (isForeground) onLocationGranted(false)
            }
        }
        getProvider()
    }

    @SuppressLint("MissingPermission")
    private fun getProvider() {
        val list = locationManager?.getProviders(true)

        val provider = when {
            list?.contains(LocationManager.GPS_PROVIDER) == true -> LocationManager.NETWORK_PROVIDER
            list?.contains(LocationManager.NETWORK_PROVIDER) == true -> LocationManager.NETWORK_PROVIDER
            else -> null
        }

        if (provider != null) {
            val location = locationManager?.getLastKnownLocation(provider)
            if (location != null) {
                LogUtils.e("------------------")
//                currentLocation = LatLng(location.latitude, location.longitude)
            }
            locationManagerRequestLocationUpdates()
        }
    }

    @SuppressLint("MissingPermission")
    private fun locationManagerRequestLocationUpdates() {
        release()
        for (provider in listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER)) {
            if (locationManager?.isProviderEnabled(provider) == true) {
                locationListener?.let {
                    locationManager?.requestLocationUpdates(
                        provider, 2000, 10f, it
                    )   // 这里的数字可以看源码注释，没需求的话，可以不用改。
                }
            }
        }
    }

    // 转换结果编码。获取省市区街道等信息。
    fun getAddress(context: Context, location: Location): Address? {
        val gc = Geocoder(context, Locale.getDefault())
        val result = try {
            gc.getFromLocation(location.latitude, location.longitude, 1)
        } catch (e: Exception) {
            listOf<Address>()
        }
        if (!result.isNullOrEmpty()) {
            return result[0]
        }
        //  省  address?.adminArea    市 address?.locality   区： address?.subLocality
        return null
    }

    fun release() {
        locationListener?.let {
            locationManager?.removeUpdates(it)
        }
    }


    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    private fun isOPenGPS(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        // GPS定位
        val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        // 网络服务定位
        val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        return gps || network
    }

}